<template>
  <div class="news-form-component">
    <!-- 表单内容 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="news-form"
    >
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧主要信息 -->
        <div class="lg:col-span-2 space-y-6">
          <!-- 基本信息 -->
          <el-card shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">基本信息</h3>
            </template>
            
            <!-- 编辑模式下显示新闻ID -->
            <el-form-item v-if="mode === 'edit'" label="新闻ID">
              <el-input v-model="formData.id" disabled />
            </el-form-item>

            <el-form-item label="新闻标题" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入新闻标题"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="新闻摘要" prop="summary">
              <el-input
                v-model="formData.summary"
                type="textarea"
                placeholder="请输入新闻摘要"
                :rows="3"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="原始链接" prop="url">
              <el-input
                v-model="formData.url"
                placeholder="请输入原始新闻链接"
              />
            </el-form-item>

            <el-form-item label="封面图片" prop="imageUrl">
              <el-input
                v-model="formData.imageUrl"
                placeholder="请输入封面图片链接"
              />
            </el-form-item>

            <el-form-item label="新闻作者" prop="author">
              <el-input
                v-model="formData.author"
                placeholder="请输入新闻作者姓名"
                maxlength="100"
              />
            </el-form-item>
          </el-card>

          <!-- 正文内容 -->
          <el-card shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">正文内容</h3>
            </template>
            
            <el-form-item label="正文内容" prop="content">
              <RichTextEditor
                v-model="formData.content"
                placeholder="请输入新闻正文内容"
                height="400px"
              />
            </el-form-item>
          </el-card>
        </div>

        <!-- 右侧分类信息 -->
        <div class="space-y-6">
          <el-card shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">分类信息</h3>
            </template>
            
            <el-form-item label="新闻分类" prop="categoryId">
              <el-select
                v-model="formData.categoryId"
                placeholder="请选择新闻分类"
                class="w-full"
                @change="handleCategoryChange"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="新闻来源" prop="sourceId">
              <el-select
                v-model="formData.sourceId"
                placeholder="请选择新闻来源"
                class="w-full"
                @change="handleSourceChange"
              >
                <el-option
                  v-for="source in sources"
                  :key="source.id"
                  :label="source.name"
                  :value="source.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="formData.publishTime"
                type="datetime"
                placeholder="请选择发布时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                class="w-full"
              />
            </el-form-item>

            <el-form-item label="新闻状态" prop="status">
              <el-select
                v-model="formData.status"
                placeholder="请选择新闻状态"
                class="w-full"
              >
                <el-option label="已发布" :value="1" />
                <el-option label="草稿" :value="0" />
                <el-option label="已下架" :value="-1" />
              </el-select>
            </el-form-item>

            <el-form-item label="是否热门" prop="isHot">
              <el-switch
                v-model="formData.isHot"
                :active-value="1"
                :inactive-value="0"
                active-text="热门"
                inactive-text="普通"
              />
            </el-form-item>

            <el-form-item label="浏览次数">
              <el-input v-model="formData.viewCount" disabled />
            </el-form-item>

            <el-form-item label="正文字数">
              <el-input :value="wordCount" disabled />
            </el-form-item>


          </el-card>

          <!-- 编辑模式下显示元数据 -->
          <el-card v-if="mode === 'edit'" shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">元数据</h3>
            </template>
            
            <el-form-item label="创建时间">
              <el-input v-model="formData.createdAt" disabled />
            </el-form-item>
            
            <el-form-item label="最后更新">
              <el-input :value="currentTime" disabled />
            </el-form-item>
          </el-card>


        </div>
      </div>
    </el-form>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="新闻预览"
      width="80%"
      class="preview-dialog"
    >
      <div class="preview-content">
        <div class="preview-header">
          <h2 class="text-2xl font-bold mb-2">{{ formData.title }}</h2>
          <div class="text-sm text-gray-500 mb-4">
            <span>{{ selectedCategoryName }}</span>
            <span class="mx-2">·</span>
            <span>{{ selectedSourceName }}</span>
            <span class="mx-2">·</span>
            <span>{{ formData.publishTime }}</span>
          </div>
        </div>
        
        <div v-if="formData.imageUrl" class="preview-image mb-4">
          <img :src="formData.imageUrl" alt="封面图" class="w-full max-h-64 object-cover rounded" />
        </div>
        
        <div class="preview-summary mb-4">
          <p class="text-gray-700 font-medium">{{ formData.summary }}</p>
        </div>
        
        <div class="preview-content-text">
          <div class="whitespace-pre-wrap text-gray-800">{{ formData.content }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RichTextEditor from '~/components/RichTextEditor.vue'
import { categoryAPI, sourceAPI } from '~/services/api'

// 定义组件属性
const props = defineProps({
  mode: {
    type: String,
    required: true,
    validator: (value) => ['add', 'edit'].includes(value)
  },
  newsId: {
    type: [String, Number],
    default: null
  },
  initialData: {
    type: Object,
    default: () => ({})
  }
})

// 定义事件
const emit = defineEmits(['save', 'delete', 'cancel'])

// 组件内部状态
const formRef = ref()
const saving = ref(false)
const previewVisible = ref(false)

// 表单数据
const formData = reactive({
  id: '',
  title: '',
  summary: '',
  content: '',
  author: '',
  wordCount: 0,
  viewCount: 0,
  isHot: 0,
  categoryId: null,
  categoryName: '',
  sourceId: null,
  sourceName: '',
  url: '',
  imageUrl: '',
  publishTime: '',
  status: 1,
  createdAt: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 5, max: 200, message: '标题长度应在5-200个字符之间', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入新闻摘要', trigger: 'blur' },
    { min: 10, max: 500, message: '摘要长度应在10-500个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入新闻正文', trigger: 'blur' },
    { min: 50, message: '正文内容不能少于50个字符', trigger: 'blur' }
  ],
  author: [
    { max: 100, message: '作者姓名不能超过100个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择新闻分类', trigger: 'change' }
  ],
  sourceId: [
    { required: true, message: '请选择新闻来源', trigger: 'change' }
  ],
  publishTime: [
    { required: true, message: '请选择发布时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择新闻状态', trigger: 'change' }
  ],
  url: [
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ]
}

// 分类和来源数据
const categories = ref([])
const sources = ref([])

// 计算属性
const selectedCategoryName = computed(() => {
  const category = categories.value.find(c => c.id === formData.categoryId)
  return category ? category.name : ''
})

const selectedSourceName = computed(() => {
  const source = sources.value.find(s => s.id === formData.sourceId)
  return source ? source.name : ''
})

const currentTime = computed(() => {
  return new Date().toISOString().slice(0, 19).replace('T', ' ')
})

// 实时计算正文字数
const wordCount = computed(() => {
  if (!formData.content) return 0
  // 移除HTML标签，只计算纯文本字数
  const textContent = formData.content.replace(/<[^>]*>/g, '')
  return textContent.length
})

// 加载分类和来源数据
const loadData = async () => {
  try {
    // 调用后端API加载分类和来源数据
    const [categoriesData, sourcesData] = await Promise.all([
      categoryAPI.getCategories(),
      sourceAPI.getSources()
    ])
    categories.value = categoriesData
    sources.value = sourcesData
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 初始化表单数据
const initFormData = () => {
  if (props.mode === 'add') {
    // 新增模式：设置默认值
    Object.assign(formData, {
      id: '',
      title: '',
      summary: '',
      content: '',
      author: '',
      wordCount: 0,
      viewCount: 0,
      isHot: 0,
      categoryId: null,
      categoryName: '',
      sourceId: null,
      sourceName: '',
      url: '',
      imageUrl: '',
      publishTime: new Date().toISOString().slice(0, 19),
      status: 1,
      createdAt: ''
    })
  } else if (props.mode === 'edit' && props.initialData) {
    // 编辑模式：使用传入的初始数据
    Object.assign(formData, {
      id: props.initialData.id || '',
      title: props.initialData.title || '',
      summary: props.initialData.summary || '',
      content: props.initialData.content || '',
      author: props.initialData.author || '',
      wordCount: props.initialData.wordCount || 0,
      viewCount: props.initialData.viewCount || 0,
      isHot: props.initialData.isHot || 0,
      categoryId: props.initialData.categoryId || null,
      categoryName: props.initialData.categoryName || '',
      sourceId: props.initialData.sourceId || null,
      sourceName: props.initialData.sourceName || '',
      url: props.initialData.url || '',
      imageUrl: props.initialData.imageUrl || '',
      publishTime: props.initialData.publishTime || '',
      status: props.initialData.status || 1,
      createdAt: props.initialData.createdAt || ''
    })
  }
}

// 处理分类变化
const handleCategoryChange = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  if (category) {
    formData.categoryName = category.name
  }
}

// 处理来源变化
const handleSourceChange = (sourceId) => {
  const source = sources.value.find(s => s.id === sourceId)
  if (source) {
    formData.sourceName = source.name
  }
}

// 预览新闻
const handlePreview = () => {
  if (!formData.title || !formData.summary || !formData.content) {
    ElMessage.warning('请先填写标题、摘要和正文内容')
    return
  }
  previewVisible.value = true
}

// 保存新闻
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    saving.value = true
    
    // 触发保存事件，让父组件处理
    emit('save', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

// 删除新闻
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除新闻「${formData.title}」吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 触发删除事件，让父组件处理
    emit('delete', formData.id)
  } catch {
    // 用户取消删除
  }
}

// 监听初始数据变化
watch(() => props.initialData, () => {
  if (props.mode === 'edit') {
    initFormData()
  }
}, { deep: true })

// 暴露方法给父组件
defineExpose({
  formRef,
  formData,
  validate: () => formRef.value?.validate(),
  resetFields: () => formRef.value?.resetFields(),
  handleSave,
  handleDelete,
  handlePreview,
  saving
})

// 组件初始化
onMounted(() => {
  loadData()
  initFormData()
})
</script>

<style scoped>
.news-form-component {
  @apply w-full;
}

.form-card {
  @apply border border-gray-200 ;
}

.form-card :deep(.el-card__header) {
  @apply bg-gray-50  border-b border-gray-200 ;
}

.news-form :deep(.el-form-item__label) {
  @apply text-gray-700  font-medium;
}

.preview-dialog :deep(.el-dialog__body) {
  @apply p-6;
}

.preview-content {
  @apply max-h-96 overflow-y-auto;
}

.preview-header {
  @apply border-b border-gray-200 pb-4 mb-4;
}

.preview-image img {
  @apply border border-gray-200 ;
}

.preview-summary {
  @apply bg-gray-50  p-4 rounded border-l-4 border-blue-500;
}

.preview-content-text {
  @apply leading-relaxed text-base;
}
</style>
